import os
from typing import Optional, Dict, List

from fit_py_ask_number_demo.data_managers import sqlite_manager


class SynonymManager:
    def __init__(self):
        """
        初始化同义词管理器
        """
        db_path = os.path.join(os.path.dirname(__file__), '../../database/kpi2.db')
        self.db_manager = sqlite_manager.SQLiteManager(db_path)

    def initialize_table(self):
        """
        初始化同义词表
        如果表已存在，则跳过初始化
        """
        if not self.db_manager.connection:
            self.db_manager.connect()

        try:
            cursor = self.db_manager.connection.cursor()

            # 检查表是否存在
            cursor.execute('''
            SELECT name FROM sqlite_master WHERE type='table' AND name='synonyms'
            ''')
            table_exists = cursor.fetchone()

            if table_exists:
                return

            # 创建同义词表
            cursor.execute('''
                CREATE TABLE IF NOT EXISTS synonyms (
                    id INTEGER PRIMARY KEY AUTOINCREMENT,
                    synonym TEXT NOT NULL,
                    standard_word TEXT NOT NULL,
                    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
                )
            ''')

            self.db_manager.connection.commit()
            print("synonyms 表初始化成功！")
        except Exception as e:
            print(f"初始化 synonyms 表失败: {e}")

    def list_synonyms(self, page: int, page_size: int, synonym_search: str = '', standard_word_search: str = '') -> Dict:
        """
        获取同义词列表，支持分页和搜索
        :param page: 页码
        :param page_size: 每页数量
        :param synonym_search: 搜索同义词
        :param standard_word_search: 搜索标准词
        :return: 包含分页数据和总数的字典
        """
        # 构建 WHERE 子句
        conditions = []
        if synonym_search:
            conditions.append(f"synonym LIKE '%{synonym_search}%'")
        if standard_word_search:
            conditions.append(f"standard_word LIKE '%{standard_word_search}%'")
        
        where_clause = " AND ".join(conditions) if conditions else None
        
        # 获取总数
        total_result = self.db_manager.read('synonyms', where_clause)
        total = len(total_result)
        
        # 获取分页数据
        offset = (page - 1) * page_size
        if where_clause:
            where_clause += f" ORDER BY id DESC LIMIT {page_size} OFFSET {offset}"
        else:
            where_clause = f"1=1 ORDER BY id DESC LIMIT {page_size} OFFSET {offset}"
            
        items = self.db_manager.read('synonyms', where_clause)
        
        return {
            'total': total,
            'items': items
        }

    def add_synonym(self, synonym: str, standard_word: str) -> bool:
        """
        添加新的同义词
        :param synonym: 同义词
        :param standard_word: 标准词
        :return: 是否成功
        """
        data = {
            'synonym': synonym,
            'standard_word': standard_word
        }
        return self.db_manager.create('synonyms', data)

    def update_synonym(self, synonym_id: int, synonym: str, standard_word: str) -> bool:
        """
        更新同义词
        :param synonym_id: 同义词ID
        :param synonym: 新的同义词
        :param standard_word: 新的标准词
        :return: 是否成功
        """
        data = {
            'synonym': synonym,
            'standard_word': standard_word
        }
        return self.db_manager.update('synonyms', data, f"id = {synonym_id}")

    def delete_synonym(self, synonym_id: int) -> bool:
        """
        删除同义词
        :param synonym_id: 同义词ID
        :return: 是否成功
        """
        return self.db_manager.delete('synonyms', f"id = {synonym_id}")

    def get_standard_word(self, synonym: str) -> Optional[str]:
        """
        根据同义词查询对应的标准词
        :param synonym: 同义词
        :return: 标准词，如果未找到则返回同义词本身
        """
        result = self.db_manager.read('synonyms', f"synonym = '{synonym}'")
        return result[0]['standard_word'] if result else synonym 